<?php

namespace app\api\controller;

use app\common\controller\Api;
use app\common\library\Ems;
use app\common\library\Sms;
use app\common\model\Artificer;
use app\common\model\Collect;
use app\common\model\mall\Coupon;
use app\common\model\Pay;
use app\common\model\PayRefund;
use app\common\model\Store;
use fast\Random;
use think\Config;
use think\Db;
use think\Exception;
use think\Log;
use think\Validate;

/**
 * 会员接口
 */
class User extends Api
{
    protected $noNeedLogin = ['login', 'mobilelogin', 'register', 'resetpwd', 'changeemail', 'third'];
    protected $noNeedRight = '*';

    public function _initialize()
    {
        parent::_initialize();

        if (!Config::get('fastadmin.usercenter')) {
            $this->error(__('User center already closed'));
        }

    }

    /**
     * 会员中心
     */
    public function index()
    {
        $car = \db('user_car')->where(['user_id'=> [ '=',$this->auth->id ] ])->field('id,vehicle_type,license_plate_number,image')->find();
        $enterState = '20';
        if($this->auth->identity == '20'){
            $enterModel = new Store();
        }
        if($this->auth->identity == '30'){
            $enterModel = new Artificer();
        }
        if(isset($enterModel)){
            $enterState = $enterModel->where(['user_id'=>['=',$this->auth->id]])->order('id desc')->value('state');
        }
        $data = [
            'nickname' => $this->auth->nickname,
            'avatar' => $this->auth->avatar,
            'identity' => $this->auth->identity,
            'carNum' => 0,
            'money' => 0,
            'couponNum' => 0,
            'gender' => $this->auth->gender,
            'birthday' => $this->auth->birthday,
            'mobile' => $this->auth->mobile,
            'license_plate_number' => $car ? $car['license_plate_number'] : '',
            'vehicle_type' => $car ? $car['vehicle_type'] : '',
            'withdraw_account' => \db('user_withdraw_account')->where('user_id' , $this->auth->id)->order('type desc')->field('type,name')->select(),
            'enterState' => $enterState,
        ];
        $this->success('会员中心', $data);
    }

    /**
     * 会员登录
     *
     * @ApiMethod (POST)
     * @param string $account  账号
     * @param string $password 密码
     */
    public function login()
    {
        $account = $this->request->post('account');
        $password = $this->request->post('password');
        if (!$account || !$password) {
            $this->error(__('Invalid parameters'));
        }
        $ret = $this->auth->login($account, $password);
        if ($ret) {
            $data = ['userinfo' => $this->auth->getUserinfo()];
            $this->success(__('Logged in successful'), $data);
        } else {
            $this->error($this->auth->getError());
        }
    }

    /**
     * 手机验证码登录
     *
     * @ApiMethod (POST)
     * @param string $mobile  手机号
     * @param string $captcha 验证码
     */
    public function mobilelogin()
    {
        $mobile = $this->request->post('mobile');
        $captcha = $this->request->post('captcha');
        if (!$mobile || !$captcha) {
            $this->error(__('Invalid parameters'));
        }
        if (!Validate::regex($mobile, "^1\d{10}$")) {
            $this->error(__('Mobile is incorrect'));
        }
        if (!Sms::check($mobile, $captcha, 'mobilelogin')) {
            $this->error(__('Captcha is incorrect'));
        }
        $user = \app\common\model\User::getByMobile($mobile);
        if ($user) {
            if ($user->status != 'normal') {
                $this->error(__('Account is locked'));
            }
            //如果已经有账号则直接登录
            $ret = $this->auth->direct($user->id);
        } else {
            $ret = $this->auth->register($mobile, Random::alnum(), '', $mobile, []);
        }
        if ($ret) {
            Sms::flush($mobile, 'mobilelogin');
            $data = ['userinfo' => $this->auth->getUserinfo()];
            $this->success(__('Logged in successful'), $data);
        } else {
            $this->error($this->auth->getError());
        }
    }

    /**
     * 注册会员
     *
     * @ApiMethod (POST)
     * @param string $username 用户名
     * @param string $password 密码
     * @param string $email    邮箱
     * @param string $mobile   手机号
     * @param string $code     验证码
     */
    public function register()
    {
        $username = $this->request->post('username');
        $password = $this->request->post('password');
        $email = $this->request->post('email');
        $mobile = $this->request->post('mobile');
        $code = $this->request->post('code');
        $distribution_code = $this->request->post('distribution_code');
        if (!$mobile || !$password) {
            $this->error(__('Invalid parameters'));
        }
        if ($email && !Validate::is($email, "email")) {
            $this->error(__('Email is incorrect'));
        }
        if ($mobile && !Validate::regex($mobile, "^1\d{10}$")) {
            $this->error(__('Mobile is incorrect'));
        }
        $ret = Sms::check($mobile, $code, 'register');
        if (!$ret) {
            $this->error(__('Captcha is incorrect'));
        }
        $ret = $this->auth->register($username, $password, $email, $mobile, ['distribution_code'=>$distribution_code]);
        if ($ret) {
            $data = ['userinfo' => $this->auth->getUserinfo()];
            $this->success(__('Sign up successful'), $data);
        } else {
            $this->error($this->auth->getError());
        }
    }

    /**
     * 退出登录
     * @ApiMethod (POST)
     */
    public function logout()
    {
        if (!$this->request->isPost()) {
            $this->error(__('Invalid parameters'));
        }
        $this->auth->logout();
        $this->success(__('Logout successful'));
    }

    /**
     * 修改会员个人信息
     *
     * @ApiMethod (POST)
     * @param string $avatar   头像地址
     * @param string $username 用户名
     * @param string $nickname 昵称
     * @param string $bio      个人简介
     */
    public function profile()
    {
        $user = $this->auth->getUser();
        $username = $this->request->post('username');
        $nickname = $this->request->post('nickname');
        $bio = $this->request->post('bio');
        $avatar = $this->request->post('avatar', '', 'trim,strip_tags,htmlspecialchars');
        $gender = $this->request->post('gender');   // 性别:female=女,male=男
        $birthday = $this->request->post('birthday');   //生日
        if(empty($nickname) && empty($avatar)  && empty($gender)  && empty($birthday)){
            $this->error('参数缺失');
        }
        if ($username) {
            $exists = \app\common\model\User::where('username', $username)->where('id', '<>', $this->auth->id)->find();
            if ($exists) {
                $this->error(__('Username already exists'));
            }
            $user->username = $username;
        }
        if ($nickname) {
            $exists = \app\common\model\User::where('nickname', $nickname)->where('id', '<>', $this->auth->id)->find();
            if ($exists) {
                $this->error(__('Nickname already exists'));
            }
            $user->nickname = $nickname;
        }
        if ($bio) {
            $user->bio = $bio;
        }
        if($avatar){
            $user->avatar = $avatar;
        }
        if($gender){
            $user->gender = $gender;
        }
        if($birthday){
            $user->birthday = $birthday;
        }
        $user->save();
        $this->success('操作成功');
    }

    /**
     * 修改邮箱
     *
     * @ApiMethod (POST)
     * @param string $email   邮箱
     * @param string $captcha 验证码
     */
    public function changeemail()
    {
        $user = $this->auth->getUser();
        $email = $this->request->post('email');
        $captcha = $this->request->post('captcha');
        if (!$email || !$captcha) {
            $this->error(__('Invalid parameters'));
        }
        if (!Validate::is($email, "email")) {
            $this->error(__('Email is incorrect'));
        }
        if (\app\common\model\User::where('email', $email)->where('id', '<>', $user->id)->find()) {
            $this->error(__('Email already exists'));
        }
        $result = Ems::check($email, $captcha, 'changeemail');
        if (!$result) {
            $this->error(__('Captcha is incorrect'));
        }
        $verification = $user->verification;
        $verification->email = 1;
        $user->verification = $verification;
        $user->email = $email;
        $user->save();

        Ems::flush($email, 'changeemail');
        $this->success();
    }

    /**
     * 修改登录密码
     *
     * @ApiMethod (POST)
     * @param string $original  原始密码
     * @param string $password 新密码
     * @param string $password_confirm 确认密码
     */
    public function changepassword()
    {
        $user = $this->auth->getUser();
        $original = $this->request->post('original');
        $password = $this->request->post('password');
        $password_confirm = $this->request->post('password_confirm');
        if (!$original || !$password || !$password_confirm) {
            $this->error(__('Invalid parameters'));
        }
        try {
            if($this->auth->getEncryptPassword($original,$user->salt) !== $user->password){
                $this->error('原始密码错误');
            }
            if($password !== $password_confirm){
                $this->error('确认密码错误');
            }
            $salt = Random::alnum();
            $user->salt = $salt;
            $user->password = $this->auth->getEncryptPassword($password,$salt);
            $user->save();
            $this->success('SUCCESS');
        }catch (Exception $e){
            $this->error('网络繁忙，请稍后再试');
        }
    }

    /**
     * 修改手机号
     *
     * @ApiMethod (POST)
     * @param string $mobile  手机号
     * @param string $captcha 验证码
     */
    public function changemobile()
    {
        $user = $this->auth->getUser();
        $mobile = $this->request->post('mobile');
        $captcha = $this->request->post('captcha');
        if (!$mobile || !$captcha) {
            $this->error(__('Invalid parameters'));
        }
        if (!Validate::regex($mobile, "^1\d{10}$")) {
            $this->error(__('Mobile is incorrect'));
        }
        if (\app\common\model\User::where('mobile', $mobile)->where('id', '<>', $user->id)->find()) {
            $this->error(__('Mobile already exists'));
        }
        $result = Sms::check($mobile, $captcha, 'changemobile');
        if (!$result) {
            $this->error(__('Captcha is incorrect'));
        }
        $verification = $user->verification;
        $verification->mobile = 1;
        $user->verification = $verification;
        $user->mobile = $mobile;
        $user->save();

        Sms::flush($mobile, 'changemobile');
        $this->success('SUCCESS');
    }

    /**
     * 第三方登录
     *
     * @ApiMethod (POST)
     * @param string $platform 平台名称
     * @param string $code     Code码
     */
    public function third()
    {
        $url = url('user/index');
        $platform = $this->request->post("platform");
        $code = $this->request->post("code");
        $config = get_addon_config('third');
        if (!$config || !isset($config[$platform])) {
            $this->error(__('Invalid parameters'));
        }
        $app = new \addons\third\library\Application($config);
        //通过code换access_token和绑定会员
        $result = $app->{$platform}->getUserInfo(['code' => $code]);
        if ($result) {
            $loginret = \addons\third\library\Service::connect($platform, $result);
            if ($loginret) {
                $data = [
                    'userinfo'  => $this->auth->getUserinfo(),
                    'thirdinfo' => $result
                ];
                $this->success(__('Logged in successful'), $data);
            }
        }
        $this->error(__('Operation failed'), $url);
    }

    /**
     * 重置密码
     *
     * @ApiMethod (POST)
     * @param string $mobile      手机号
     * @param string $newpassword 新密码
     * @param string $captcha     验证码
     */
    public function resetpwd()
    {
        $type = $this->request->post("type", "mobile");
        $mobile = $this->request->post("mobile");
        $email = $this->request->post("email");
        $newpassword = $this->request->post("newpassword");
        $newpassword_confirm = $this->request->post("newpassword_confirm");
        $captcha = $this->request->post("captcha");
        if (!$newpassword || !$captcha || !$newpassword_confirm) {
            $this->error(__('Invalid parameters'));
        }
        if($newpassword_confirm !== $newpassword){
            $this->error(__('两次新密码不一致'));
        }
        //验证Token
        if (!Validate::make()->check(['newpassword' => $newpassword], ['newpassword' => 'require|regex:\S{6,30}'])) {
            $this->error(__('Password must be 6 to 30 characters'));
        }
        if ($type == 'mobile') {
            if (!Validate::regex($mobile, "^1\d{10}$")) {
                $this->error(__('Mobile is incorrect'));
            }
            $user = \app\common\model\User::getByMobile($mobile);
            if (!$user) {
                $this->error(__('User not found'));
            }
            $ret = Sms::check($mobile, $captcha, 'resetpwd');
            if (!$ret) {
                $this->error(__('Captcha is incorrect'));
            }
            Sms::flush($mobile, 'resetpwd');
        } else {
            if (!Validate::is($email, "email")) {
                $this->error(__('Email is incorrect'));
            }
            $user = \app\common\model\User::getByEmail($email);
            if (!$user) {
                $this->error(__('User not found'));
            }
            $ret = Ems::check($email, $captcha, 'resetpwd');
            if (!$ret) {
                $this->error(__('Captcha is incorrect'));
            }
            Ems::flush($email, 'resetpwd');
        }
        //模拟一次登录
        $this->auth->direct($user->id);
        $ret = $this->auth->changepwd($newpassword, '', true);
        if ($ret) {
            $this->success(__('Reset password successful'));
        } else {
            $this->error($this->auth->getError());
        }
    }

    /**
     * 我的爱车
     * @return void
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function car()
    {
        $info = \db('user_car')->where(['user_id'=> [ '=',$this->auth->id ] ])->field('id,vehicle_type,license_plate_number,image')->find();
        if($info){
            $info['image'] = $info['image'] ? cdnurl($info['image'],true) : '';
        }
        $list = null;
        $data = [
            'id' => $info ? $info['id'] : 0,
            'vehicle_type' => $info ? $info['vehicle_type'] : '',
            'license_plate_number' => $info ? $info['license_plate_number'] : '',
            'image' => $info && $info['image'] ? cdnurl($info['image'],true) : '',
            'list' => $list
        ];
        $this->success('我的爱车',$data);
    }

    /**
     * 天机编辑爱车
     * @return void
     */
    public function saveCar()
    {
        try {
            $id = $this->request->post('id');
            //车型   车牌号   图像
            $vehicle_type = $this->request->post('vehicle_type');
            $license_plate_number = $this->request->post('license_plate_number');
            $image = $this->request->post('image');
            if(!$vehicle_type || !$image){
                $this->error('参数缺失');
            }
            if ($id){
                if(! \db('user_car')->where(['id' => ['=',$id],'user_id' => ['=',$this->auth->id]])->find()){
                    $this->error('参数错误');
                }
                $res = \db('user_car')->where(['id' => ['=',$id],'user_id' => ['=',$this->auth->id]])->update([
                    'vehicle_type' => $vehicle_type,
                    'license_plate_number' => $license_plate_number,
                    'image' => $image,
                    'updatetime' => time(),
                ]);
            }else{
                $res = \db('user_car')->insert([
                    'user_id' => $this->auth->id,
                    'vehicle_type' => $vehicle_type,
                    'license_plate_number' => $license_plate_number,
                    'image' => $image,
                    'createtime' => time(),
                    'updatetime' => time(),
                ]);
            }
            if($res === false){
                throw new Exception('操作失败');
            }
            $this->success('操作成功');
        }catch (Exception $e){
            Log::write($e->getMessage(),'error',true);
            $this->error('网络繁忙，请稍后再试');
        }
    }

    /**
     * 删除爱车
     * @return void
     */
    public function delCar()
    {
        try {
            $id = $this->request->post('id');
            if(!$id){
                $this->error('参数缺失');
            }
            if(! \db('user_car')->where(['id' => ['=',$id],'user_id' => ['=',$this->auth->id]])->find()){
                $this->error('参数错误');
            }
            $res = \db('user_car')->where(['id' => ['=',$id],'user_id' => ['=',$this->auth->id]])->delete();
            if($res === false){
                throw new Exception('操作失败');
            }
            $this->success('操作成功');
        }catch (Exception $e){
            Log::write($e->getMessage(),'error',true);
            $this->error('网络繁忙，请稍后再试');
        }
    }

    /**
     * 商家入驻
     * @return void
     * @throws \Exception
     */
    public function businessCheckin()
    {
        Db::startTrans();
        try {
            $user = $this->auth->getUser();
            if($user->identity === '30'){
                $this->error('技工不可申请入驻商家');
            }
            $params = $this->request->post();
            extract($params);
            if(empty($shop_name) || empty($business_hours) || empty($address) || empty($owner_name) || empty($owner_mobile) || empty($telephone) || empty($vehicle_type) || empty($category_ids) || empty($shop_intro) || empty($logo_image) || empty($shop_door_image) || empty($prove_images) || empty($amount)){
                $this->error('参数缺失');
            }
            $model = new Store();
            //删除 已退款的记录
            $model->where(['user_id'=>['=',$this->auth->id],'refund_status'=>['=','20']])->delete();
            (new Artificer())->where(['user_id'=>['=',$this->auth->id],'refund_status'=>['=','20']])->delete();
            //判断是否是审核失败；如果是审核失败，就修改
            $row = $model->where(['user_id'=>['=',$this->auth->id]])->find();
            if($row){
                if($row->state == '20'){
                    $this->error('审核通过，不可重复提交');
                }
                if($row->state == '10'){
                    $this->error('审核中，不可重复提交');
                }
                if($row->state == '30'){
                    $model = $row;
                    $params['state'] = '10';
                    $params['reason'] = '';
                }
            }
            $params['user_id'] = $this->auth->id;
            $params['pay_way'] = (isset($pay_way) && $pay_way) ? $pay_way : null;
            $result = $model->allowField(true)->save($params);
            if ($result === false) {
                exception($model->getError());
            }
            $user->identity = '20';
            $user->save();
            $store_id = $model->id;
            $data = null;
            $msg = '提交成功，资料审核中';
            //未支付，去支付
            if($pay_status == '10'){
                if( (!isset($pay_way)) || empty($pay_way)){
                    $this->error('参数pay_way缺失');
                }
                if($pay_way == '30'){
                    //余额支付
                    $userModel = new \app\common\model\User();
                    $result = $userModel->money(-$amount,$this->auth->id,'商家入驻',1,$store_id);
                    if($result === false){
                        $this->error($userModel->getError());
                    }
                    //改变支付状态
                    $model->where('id',$store_id)->update(['pay_status'=>'20','paytime'=>time()]);
                }else{
                    $payTypeArr = ['10'=>'wechat','20'=>'alipay'];
                    if(!isset($payTypeArr[$pay_way])){
                        $this->error('支付类型错误');
                    }
                    $payModel = new Pay();
                    $data = $payModel->createPay($this->auth->id,1,$store_id,$payTypeArr[$pay_way],'api/index/notify/paytype/'.$payTypeArr[$pay_way],'','商家入驻');
                    if($payModel->hasError()){
                        $this->error($payModel->getError());
                    }
                    $msg = '去支付';
                    //测试 回调
                    $payModel->notify($data,Random::alnum(18));
                }
            }
            Db::commit();
        }catch (Exception $e){
            Db::rollback();
            Log::write($e->getMessage(),'error',true);
            $this->error('网络繁忙，请稍后再试');
        }
        $this->success($msg,$data);
    }

    /**
     * 商家入驻信息
     * @return void
     */
    public function businessCheckinInfo()
    {
        try {
            $model = new Store();
            $row = $model->where(['user_id'=>['=',$this->auth->id]])->field(['verifytime','total_sales','sales','false_sales','likes','collect','recommend_switch','weigh','paytime','createtime','updatetime','deletetime'],true)->find();
            if(empty($row)){
                $this->error('请提交入驻资料');
            }
            switch ($row->state){
                case '10':
                    $row->msg = '请耐心等待，若等待超过3天可联系平台 '.\app\common\model\Config::getValue('platform_phone','basic');
                    break;
                case '20':
                    $row->msg =  '恭喜您，入驻商家成功';
                    break;
                case '30':
                    $row->msg =  '被驳回原因：'.$row->reason;
                    break;
                default:
                    $this->error('参数错误');
            }
            $this->success('商家入驻信息',$row);
        }catch (Exception $e){
            Log::write($e->getMessage(),'error',true);
            $this->error('网络繁忙，请稍后再试');
        }
    }

    /**
     * 商家入驻审核失败申请退款
     * @return void
     * @throws \Exception
     */
    public function businessCheckinRefund()
    {
        try {
            $model = new Store();
            $row = $model->where(['user_id'=>['=',$this->auth->id],'state'=>['=','30']])->find();
            if(empty($row)){
                $this->error('参数错误');
            }
            if($row->state !== '30'){
                $this->error('入驻资料驳回，方可申请退款');
            }
            //退款
            $payRefund = new PayRefund();
            $payRefund->createRefundPay($this->auth->id,1,$row->id,'退款');
            if($payRefund->hasError()){
                $this->error($payRefund->getError());
            }
            $this->success('success');
        }catch (Exception $e){
            Log::write($e->getMessage(),'error',true);
            $this->error('网络繁忙，请稍后再试');
        }
    }

    /**
     * 技工入驻
     * @return void
     * @throws \Exception
     */
    public function artificerCheckin()
    {
        Db::startTrans();
        try {
            $user = $this->auth->getUser();
            if($user->identity === '20'){
                $this->error('商家不可申请入驻技工');
            }
            $params = $this->request->post();
            extract($params);
            if(empty($name) || empty($mobile) || empty($address) || empty($vehicle_type) || empty($category_ids) || empty($self_intro) || empty($aptitude_images) || empty($amount)){
                $this->error('参数缺失');
            }
            $model = new Artificer();
            //删除 已退款的记录
            $model->where(['user_id'=>['=',$this->auth->id],'refund_status'=>['=','20']])->delete();
            (new Store())->where(['user_id'=>['=',$this->auth->id],'refund_status'=>['=','20']])->delete();
            //判断是否是审核失败；如果是审核失败，就修改
            $row = $model->where(['user_id'=>['=',$this->auth->id]])->find();
            if($row){
                if($row->state == '20'){
                    $this->error('审核通过，不可重复提交');
                }
                if($row->state == '10'){
                    $this->error('审核中，不可重复提交');
                }
                if($row->state == '30'){
                    $model = $row;
                    $params['state'] = '10';
                    $params['reason'] = '';
                }
            }
            $params['user_id'] = $this->auth->id;
            $params['pay_way'] = (isset($pay_way) && $pay_way) ? $pay_way : null;
            $result = $model->allowField(true)->save($params);
            if ($result === false) {
                exception($model->getError());
            }
            $user->identity = '30';
            $user->save();
            $artificer_id = $model->id;
            $data = null;
            $msg = '提交成功，资料审核中';
            //未支付，去支付
            if($pay_status == '10'){
                if( (!isset($pay_way)) || empty($pay_way)){
                    $this->error('参数pay_way缺失');
                }
                if($pay_way == '30'){
                    //余额支付
                    $userModel = new \app\common\model\User();
                    $result = $userModel->money(-$amount,$this->auth->id,'技工入驻',2,$artificer_id);
                    if($result === false){
                        $this->error($userModel->getError());
                    }
                    //改变支付状态
                    $model->where('id',$artificer_id)->update(['pay_status'=>'20','paytime'=>time()]);
                }else{
                    $payTypeArr = ['10'=>'wechat','20'=>'alipay'];
                    if(!isset($payTypeArr[$pay_way])){
                        $this->error('支付类型错误');
                    }
                    $payModel = new Pay();
                    $data = $payModel->createPay($this->auth->id,2,$artificer_id,$payTypeArr[$pay_way],'api/index/notify/paytype/'.$payTypeArr[$pay_way],'','商家入驻');
                    if($payModel->hasError()){
                        $this->error($payModel->getError());
                    }
                    $msg = '去支付';
                    //测试 回调
                    $payModel->notify($data,Random::alnum(18));
                }
            }
            Db::commit();
        }catch (Exception $e){
            Db::rollback();
            Log::write($e->getMessage(),'error',true);
            $this->error('网络繁忙，请稍后再试');
        }
        $this->success($msg,$data);
    }

    /**
     * 技工入驻信息
     * @return void
     */
    public function artificerCheckinInfo()
    {
        try {
            $model = new Artificer();
            $row = $model->where(['user_id'=>['=',$this->auth->id]])->field(['verifytime','weigh','paytime','createtime','updatetime','deletetime'],true)->find();
            if(empty($row)){
                $this->error('请提交入驻资料');
            }
            switch ($row->state){
                case '10':
                    $row->msg = '请耐心等待，若等待超过3天可联系平台 '.\app\common\model\Config::getValue('platform_phone','basic');
                    break;
                case '20':
                    $row->msg =  '恭喜您，技工入驻成功';
                    break;
                case '30':
                    $row->msg =  '被驳回原因：'.$row->reason;
                    break;
                default:
                    $this->error('参数错误');
            }
            $this->success('技工入驻信息',$row);
        }catch (Exception $e){
            Log::write($e->getMessage(),'error',true);
            $this->error('网络繁忙，请稍后再试');
        }
    }

    /**
     * 技工入驻审核失败申请退款
     * @return void
     * @throws \Exception
     */
    public function artificerCheckinRefund()
    {
        try {
            $model = new Artificer();
            $row = $model->where(['user_id'=>['=',$this->auth->id],'state'=>['=','30']])->find();
            if(empty($row)){
                $this->error('参数错误');
            }
            if($row->state !== '30'){
                $this->error('入驻资料驳回，方可申请退款');
            }
            //退款
            $payRefund = new PayRefund();
            $payRefund->createRefundPay($this->auth->id,2,$row->id,'退款');
            if($payRefund->hasError()){
                $this->error($payRefund->getError());
            }
            $this->success('success');
        }catch (Exception $e){
            Log::write($e->getMessage(),'error',true);
            $this->error('网络繁忙，请稍后再试');
        }
    }

    /**
     * 收货地址列表
     * @return void
     */
    public function addressLists()
    {
        $addressModel = new \app\common\model\Address();
        $list =  $addressModel->getList($this->auth->id);
        $this->success('success',$list);
    }

    /**
     * 添加、编辑 收货地址
     * @return null
     */
    public function saveAddress()
    {
        $id = $this->request->post('id');
        $addressModel = new \app\common\model\Address();
        if(empty($id)){
            if ($addressModel->add($this->auth->id, $this->request->post())) {
                return $this->success(__('Operation completed'));
            }
        }else{
            $detail = $addressModel->detail($this->auth->id,$id);
            if ($detail->edit($this->request->post())) {
                return $this->success(__('Operation completed'));
            }
        }
        return $this->error(__('Operation failed'));
    }

    /**
     * 设置默认收货地址
     * @return null
     */
    public function setdefault(){
        $addressModel = new \app\common\model\Address();
        if ($addressModel->setdefault($this->auth->id,$this->request->post('id'))){
            return $this->success(__('Operation completed'));
        }
        return $this->error(__('Operation failed'));
    }

    /**
     * 删除收货地址
     * @return null
     */
    public function delAddress()
    {
        $id = $this->request->post('id');
        $addressModel = new \app\common\model\Address();
        $detail = $addressModel->detail($this->auth->id,$id);
        if(empty($detail)){
            $this->error(__('Invalid parameters'));
        }
        if ($addressModel->del($id)) {
            return $this->success(__('Operation completed'));
        }
        return $this->error(__('Operation failed'));
    }

    /**
     * 地址详情
     * @return null
     */
    public function detailAddress(){
        $id = $this->request->post('id');
        $addressModel = new \app\common\model\Address();
        $detail = $addressModel->detail($this->auth->id,$id);
        if(empty($detail)){
            $this->error(__('Invalid parameters'));
        }
        $rArea = array_values($detail['Area']);
        return $this->success(__('Operation completed'),$detail);
    }

    /**
     * 获取默认收货地址
     * @return null
     */
    public function defaultAddress(){
        $detail = \app\common\model\Address::getdefault($this->auth->id);
        if(empty($detail)){
            $this->error('请设置默认地址');
        }
        return $this->success(__('success'),$detail);
    }

    /**
     * 绑定提现账户
     * @return void
     */
    public function withdrawAccount()
    {
        try {
            $param = $this->request->param();
            extract($param);
            if(empty($type) || empty($phone) || empty($image) || empty($name)){
                $this->error('参数缺失');
            }
            if(!in_array($type,['10','20'])){
                $this->error(__('Invalid parameters'));
            }
            $param['updatetime'] = time();
            if(\db('user_withdraw_account')->where(['user_id'=>['=',$this->auth->id] , 'type' => ['=',$type]])->find()){
                \db('user_withdraw_account')->where(['user_id'=>['=',$this->auth->id] , 'type' => ['=',$type]])->update($param);
            }else{
                $param['user_id'] = $this->auth->id;
                $param['createtime'] = time();
                \db('user_withdraw_account')->insert($param);
            }
            $this->success(__('Operation completed'));
        }catch (Exception $e){
            $this->success(__('Network error'));
        }
    }

    /**
     * 提现账户-解绑
     * @return void
     */
    public function untieWithdrawAccount()
    {
        try {
            $type = $this->request->param('type');
            if(!in_array($type,['10','20'])){
                $this->error(__('Invalid parameters'));
            }
            \db('user_withdraw_account')->where(['user_id'=>['=',$this->auth->id] , 'type' => ['=',$type]])->delete();
            $this->success(__('Operation completed'));
        }catch (Exception $e){
            $this->success(__('Network error'));
        }
    }

    /**
     * 我的反馈
     * @return void
     */
    public function feedbackList()
    {
        try {
            $list = \db('user_feedback')->where(['user_id'=>['=',$this->auth->id]])->field('problem,phone,createtime')->select();
            if($list){
                foreach ($list as $k=>&$v){
                    $v['createtime'] = date('Y-m-d',$v['createtime']);
                }
            }
            $this->success('OK',$list);
        }catch (Exception $e){
            $this->success(__('Network error'));
        }
    }

    /**
     * 意见反馈
     * @return void
     */
    public function addFeedback()
    {
        try {
            $param = $this->request->param();
            extract($param);
            if(empty($phone) || empty($problem)){
                $this->error(__('Invalid parameters'));
            }
            $param['user_id'] = $this->auth->id;
            $param['createtime'] = time();
            $param['updatetime'] = time();
            \db('user_feedback')->insert($param);
            $this->success(__('Operation completed'));
        }catch (Exception $e){
            $this->success(__('Network error'));
        }
    }

    /**
     * 收藏列表
     * @return void
     */
    public function collectList()
    {
        try {
            $limit = $this->request->post('limit/d',10);
            $page = $this->request->post('page/d',1);
            $type = $this->request->post('type'); //类型:10=商家,20=商品
            if(empty($type) || (!in_array($type,['10','20'])) ){
                $this->error(__('Invalid parameters'));
            }
            $collectModel = new Collect();
            $list = $collectModel->where(['user_id'=>['=',$this->auth->id],'type'=>['=',$type]])
                ->paginate($limit,false,['page'=>$page])
                ->each(function ($item){
                    $temp = $item->commentable;
                    if($item->type == '10'){
                        $item->name = $temp->shop_name;
                        $item->logo_image = $temp->logo_image_url;
                        $item->categoryArr = isset($temp->category_text) ? explode('、',$temp->category_text) : [];
                        $item->distance = 0;
                    }
                    if($item->type == '20'){
                        $item->name = $temp->name;
                        $item->logo_image = $temp->image_url;
                        $item->price = $temp->price;
                        $item->market_price = $temp->market_price;
                        $item->total_sales = $temp->total_sales;
                        $item->store_name = $temp->store->shop_name;
                        $item->store_logo_image = $temp->store->logo_image_url;
                        $item->store_location = ['lng'=>$temp->store->lng,'lat'=>$temp->store->lat];
                        //优惠券
                        $coupon = [];
                        if($temp->coupon_switch && $temp->store->coupon){
                            foreach ($temp->store->coupon as $k=>$v){
                                if($v->endtime > time()){
                                    $tempCoupon = ['id' => $v->id,'title'=> $v->getData('title'),'endtime' => $v->endtime,'quantity'=>$v->quantity];
                                    $coupon[] = $tempCoupon;
                                }
                            }
                        }
                        //array_unique  移除数组中重复的值
                        $coupon = array_unique($coupon, SORT_REGULAR);
                        //二维数组，根据某字段排序
                        array_multisort(array_column($coupon,'endtime'), SORT_ASC, SORT_NUMERIC,$coupon);
                        $item->coupon = $coupon;
                    }
                    unset($item->commentable);
                    return $item;
                });
            $this->success(__('success'),$list);
        }catch (Exception $e){
            Log::write('错误信息：'.$e->getMessage(),'error',true);
            $this->error(__('Network error'));
        }
    }

    /**
     * 删除收藏
     * @return void
     */
    public function delcollect()
    {
        try {
            $ids = $this->request->post('ids');
            if(empty($ids)){
                $this->error(__('Invalid parameters'));
            }
            $result = Collect::destroy($ids);
            if($result === false){
                $this->error(__('No rows were deleted'));
            }
            $this->success(__('Operation completed'));
        }catch (Exception $e){
            $this->success(__('Network error'));
        }
    }

    /**
     * 优惠券列表
     * @return void
     */
    public function couponList()
    {
        try {
            $status = $this->request->post('status');
            $where = ['switch'=>['=',1],'starttime'=>['<',time()],'endtime'=>['>',time()]];
            $result = Coupon::where($where)->order('weigh desc,id desc')->select();
            $list = [];
            if($result){
               foreach ($result as $k=>&$v){
                   $temp = [
                       'id' => $v->id,
                       'title' => $v->title,
                       'threshold_value' => $v->threshold_value,
                       'quantity' => $v->quantity,
                       'starttime' => $v->starttime_text,
                       'endtime' => $v->endtime_text,
                       'scope' => '指定商品',
                       'obtain' => (bool)$v->usercoupon()->where('user_id',$this->auth->id)->where('use_switch',0)->select(),
                   ];
                   if(isset($status) && ($status == '10') && (!$temp['obtain'])){
                       //待领取
                       $list[] = $temp;
                   }
                   if(isset($status) && ($status == '20') && $temp['obtain']){
                       //待使用
                       $list[] = $temp;
                   }
                   if(empty($status)){
                       $list[] = $temp;
                   }
               }
            }
            $this->success(__('SUCCESS'),$list);
        }catch (Exception $e){
            Log::write($e->getMessage(),'error',true);
            $this->success(__('Network error'));
        }
    }
}
